import { Component, OnInit, Output, EventEmitter, Input, OnChanges, SimpleChanges } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ApiShipAddressService } from '../../../../../api/system/api-ship-address.service';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: 'sda-ship-address-detail-modal',
  templateUrl: './ship-address-detail-modal.component.html',
  styleUrls: ['./ship-address-detail-modal.component.scss']
})
export class ShipAddressDetailModalComponent implements OnInit, OnChanges {

  // tslint:disable-next-line:no-output-on-prefix
  @Output()
  onSuccess = new EventEmitter<void>();

  // tslint:disable-next-line:no-input-rename
  @Input('address')
  detail: any;

  // 显示 、 隐藏
  visible = false;
  // 表单对象
  shipAddressForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private apiService: ApiShipAddressService,
    private messageService: NzMessageService
  ) { }

  ngOnInit() {
    this.initFormInstance();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (!changes.firstChange && this.shipAddressForm) {
      this.shipAddressForm.patchValue(changes.detail.currentValue || {});
    }
  }

  hide() {
    this.visible = false;
    this.reset();
  }

  show() {
    this.visible = true;
  }

  onCancel() {
    this.hide();
  }

  onSubmit(e: Event) {
    e.preventDefault();

    if (this.shipAddressForm.valid) {
      this.apiService
        .updateAddress(this.shipAddressForm.value)
        .subscribe(res => {
          this.messageService.success(res.msg);
          this.hide();
          // 成功的回调
          this.onSuccess.emit();
        });
    } else {
      // tslint:disable-next-line:forin
      for (const i in this.shipAddressForm.controls) {
        this.shipAddressForm.controls[ i ].markAsDirty();
        this.shipAddressForm.controls[ i ].updateValueAndValidity();
      }
    }
  }

  /**
   * 清空表单数据
   *
   * @memberof ShipAddressDetailModalComponent
   */
  reset() {
    this.shipAddressForm.reset();
  }

  /**
   * 初始化表单对象
   *
   * @memberof ShipAddressDetailModalComponent
   */
  initFormInstance() {
    this.shipAddressForm = this.fb.group({
      id: [ null ],
      name: [ null, Validators.required ],
      country: [ null ],
      province: [ null ],
      city: [ null ],
      addr: [ null ],
      post_code: [ null ],
      tel: [ null ]
    });
  }

}
